package stone926.mods.more_enchantments.mixins;

import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.FireballEntity;
import net.minecraft.item.FireChargeItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;
import stone926.mods.more_enchantments.enchantments.FireballThrowerEnchantment;
import stone926.mods.more_enchantments.util.EnchantmentUtil;

@Mixin(FireChargeItem.class)
public class FireChargeItemMixin extends Item {

  public FireChargeItemMixin(Settings settings) {
    super(settings);
  }

  @Override
  public ActionResult useOnBlock(ItemUsageContext context) {
    if (EnchantmentUtil.hasEnchantment(MoreEnchantmentsMod.FIREBALL_THROWER, context.getStack()))
      return ActionResult.PASS;
    return super.useOnBlock(context);
  }

  @Override
  public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
    if (!world.isClient) {
      ItemStack stack = user.getStackInHand(hand);
      boolean isCreative = user.isCreative();
      int fireballThrowerLvl = EnchantmentHelper.getLevel(MoreEnchantmentsMod.FIREBALL_THROWER, stack);

      float f1 = -MathHelper.sin(user.getYaw() * 0.017453292F) * MathHelper.cos(user.getPitch() * 0.017453292F);
      float f2 = -MathHelper.sin((user.getPitch() + user.getRoll()) * 0.017453292F);
      float f3 = MathHelper.cos(user.getYaw() * 0.017453292F) * MathHelper.cos(user.getPitch() * 0.017453292F);

      if (fireballThrowerLvl > 0 && (user.experienceLevel != 0 || isCreative)) {
        FireballEntity fireball = new FireballEntity(
          world, user,
          f1 * fireballThrowerLvl, f2 * fireballThrowerLvl, f3 * fireballThrowerLvl,
          FireballThrowerEnchantment.getExplosionPower(fireballThrowerLvl, user.getRandom())
        );
        fireball.setPosition(user.getPos().add(0, user.getHeight(), 0));
        fireball.setOwner(user);
        fireball.setVelocity(user, user.getPitch(), user.getYaw(), 0, 1F + fireballThrowerLvl / 1.5F, Math.max(0, 1 - fireballThrowerLvl * 0.12F));
        world.spawnEntity(fireball);
        stack.decrement(1);
        FireballThrowerEnchantment.damageUserRandomly(user, fireballThrowerLvl);
        if (!isCreative) {user.addExperience(-fireballThrowerLvl * 15);}
        return TypedActionResult.success(stack);
      }
    }
    return super.use(world, user, hand);
  }

}
